import {
  Column,
  Entity,
  OneToMany,
  PrimaryGeneratedColumn,
  ManyToOne,
  BeforeInsert,
  Generated,
  JoinTable,
  ManyToMany,
  PrimaryColumn,
} from 'typeorm';
import { Post } from './post.entity';
import { Role } from './role.entity';
import { BaseEntity } from '../entities/base.entity';
import * as crypto from 'crypto';
import { Poll } from './poll.entity';
import { Singer } from './singer.entity';
import { VoteRecord } from './vote-record.entity';
import { CommentSinger } from './comment.entity';

@Entity('user')
export class User extends BaseEntity {
  constructor() {
    super();
    this.id = crypto.randomBytes(8).toString('hex'); // 生成一个8字节（16个十六进制字符）的随机字符串作为id
  }
  // 自增唯一主键
  // 账户名类型
  @PrimaryColumn({ length: 225 })
  id: string;

  // 账户名类型
  @Column({ type: 'varchar', length: 255, comment: '用户姓名' })
  account: string;

  // 密码
  @Column({ type: 'varchar', length: 255, comment: '用户密码' })
  password: string;

  @Column({ type: 'varchar', length: 255, comment: '头像', nullable: true })
  avatar: string;

  @Column({ type: 'varchar', length: 255, comment: '性别', nullable: true })
  sex: string;

  // 用户名
  @Column({ type: 'varchar', length: 255, comment: '用户名' })
  username: string;

  @ManyToMany(() => Role, (role) => role.users, { cascade: true })
  @JoinTable({ name: 'user_roles' }) // 指定连接表的名称
  roles: Partial<Role>[];

  @OneToMany(() => VoteRecord, (voteRecord) => voteRecord.user, {
    cascade: true, // 自动保存相关对象
    onDelete: 'CASCADE',
  })
  voteRecords: VoteRecord[];

  @OneToMany(() => CommentSinger, (CommentSinger) => CommentSinger.user, {
    cascade: true, // 自动保存相关对象
    onDelete: 'CASCADE',
  })
  CommentSinger: CommentSinger[];

  @OneToMany(() => Poll, (poll) => poll.user, {
    cascade: true, // 自动保存相关对象
    onDelete: 'CASCADE',
  })
  poll: Poll[];
}
